import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import loadjs from 'loadjs';
import {
  WeaLocaleProvider,
  WeaCheckbox,
} from 'ecCom';
import { Button, Dropdown, Menu, Modal, message, Spin } from 'antd';
import jQuery from 'jquery';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

@inject('odocSignApprovalStore')
@observer
export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentWillMount() {
    let { setProperty } = this.props.odocSignApprovalStore;
    let { commonParam = {} } = window.parent.WfForm.getGlobalStore();
    const { workflowid, nodeid, requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
    setProperty({ workflowid, nodeid, requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype });
  }

  componentDidMount() {
    let { getSignApprovalDatas, updateHeaderPosition, setQpSelected } = this.props.odocSignApprovalStore;
    getSignApprovalDatas().then((data) => {
      if (data == true) {
        this.ayncLoadResource();
      }
    });
    window.onresize = function () {
      updateHeaderPosition();
    };
    window.odocSignApprovalStore = this.getSignApprovalStore();
  }

  getSignApprovalStore =()=>{
    return this.props.odocSignApprovalStore;
  }

  /**
   *  异步加载契约锁js sdk资源
   */
  ayncLoadResource = () => {
    const { odocSignApprovalStore } = this.props;
    let { cssPath } = odocSignApprovalStore;
    const callbackFn = () => {
      document.onclick = function () { // 去除好签css影响
        let num = 0;
        let timer = setInterval(() => {
          if (num < 5) {
            if (window.parent && window.parent.jQuery(`head>link[href='${cssPath}']`).length > 0) {
              window.parent.jQuery(`head>link[href='${cssPath}']`).remove();
            }
            num++;
          } else {
            clearInterval(timer);
          }
        }, 100);
      };
      this.loadSignApprovalPage();
    };
    loadjs.isDefined('haoqianResources') ? loadjs.ready('haoqianResources', callbackFn) : loadjs(odocSignApprovalStore.resourceFiles(), 'haoqianResources', callbackFn);
  }

  loadSignApprovalPage = () => {
    const { odocSignApprovalStore } = this.props;

    const { sequenceId, token, userid, lastname, isSeal, setProperty, saveSignApprovalDatas, defaultWriteColor, defaultWriteSize } = odocSignApprovalStore;
    // 实例化
    let ctx = new WSPCSignContext();
    let _that = this;
    // 初始化
    ctx.Init({
      el: '#ctx',
      token, // 替换此参数
      sequenceId, // 替换此参数
      callerId: `${userid}`,
      callerName: lastname,
    });
    // 渲染
    ctx.Render({
      readonly: !isSeal,
      hiddenToolbar: true,
      customSaveConfirmTitle: '',
      customSaveConfirmContent: '',
      defaultWriteColor,
      defaultWriteSize: parseInt(defaultWriteSize),
    });
    // 保存成功的回调
    ctx.On('saveSucceed', (buildno) => {
      message.success(getLabel('22619', '保存成功'), 1);
      if (_that.props.odocSignApprovalStore.isClickSave == true) {
        ctx.SimulateClickBtn('writeBtn');
        setProperty({ isClickSave: false, qpSelected: true });
      }
      saveSignApprovalDatas(buildno);
    });
    // 自定义按钮的点击回调
    ctx.On('tbBtnClick', (name) => {
      if (name === 'myBuild') { }
      // name:用户自定义按钮的名称
    });
    // 因为涉及到接口请求，在请求失败，界面无法加载的时候会把结果回调给接入者。
    // ctx.On('renderError', (msg) => {
    ctx.On('renderError', () => {
      // msg的枚举待完善。。。
    });
    ctx.On('writeClose', () => {
      setProperty({ qpSelected: false });
    });
    // 渲染成功
    // ctx.On('renderSucceed', (buildNo) => {
    ctx.On('renderSucceed', () => {
      window.signApprovalCtx = ctx;
      // 渲染成功触发事件
      _that.ctxRenderDoneEvent(ctx);
    });
  }

  ctxRenderDoneEvent = (ctx) => {
    const { odocSignApprovalStore } = this.props;
    const { isSeal, setProperty, defaultSign, qpSelected } = odocSignApprovalStore;

    if ((defaultSign && isSeal == true) || qpSelected == true) {
      ctx.SimulateClickBtn('writeBtn');
      setProperty({ qpSelected: true, defaultSign: false });
    }
    setProperty({ ctx, hasLoad: true });

    let WfForm = window.parent.WfForm;
    WfForm.registerCheckEvent(WfForm.OPER_BEFOREVERIFY, (callback) => {
      let result = WfForm.verifyFormRequired(false, true);
      if (!result) {
        WfForm.getGlobalStore().setTabKey('form');
      } else {
        callback();
      }
    });
    WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, (callback) => {
      window.signApprovalCtx.CloseWrite();
      if (window.signApprovalCtx && window.signApprovalCtx.CheckoutHasUnsaveData()) {
        window.signApprovalCtx.SimulateClickBtn('wsSaveBtn');
        setTimeout(() => {
          callback();
        }, 1000);
      } else {
        callback();
      }
    });
    WfForm.registerCheckEvent(WfForm.OPER_REJECT, (callback) => {
      window.signApprovalCtx.CloseWrite();
      if (window.signApprovalCtx && window.signApprovalCtx.CheckoutHasUnsaveData()) {
        window.signApprovalCtx.SimulateClickBtn('wsSaveBtn');
        setTimeout(() => {
          callback();
        }, 1000);
      } else {
        callback();
      }
    });
    if(isSeal==true){
      WfForm.registerCheckEvent(WfForm.OPER_SAVE, function(callback){
        window.signApprovalCtx.CloseWrite();
        if (window.signApprovalCtx && window.signApprovalCtx.CheckoutHasUnsaveData()) {
          window.signApprovalCtx.SimulateClickBtn('wsSaveBtn');
          setTimeout(() => {
            callback();
          }, 1000);
        }
      });
    }
  }


  // 添加顶部右侧其按钮
  getTopButton = () => {
    let { isviewHistory, historyVersionName, leftKeys, RrightKeys, isSeal, device, sealDocs,isDownload,downloadBtnName } = this.props.odocSignApprovalStore;
    return (<div id={'topMenu'} className={'wea-haoqian-header'}>
      <div className="haoqian-left" />
      {!isviewHistory && <div className="haoqian-middle">
        {
          toJS(leftKeys).map((item) => {
            if (!isSeal && (item.key == 'writeBtn' || item.key == 'wsSaveBtn')) {
              return;
            }
            return this.renderButton(item);
          })
        }
      </div>}
      <div className={`haoqian-right ${isviewHistory ? 'haoqian-right-history' : ''}`}>
        {isviewHistory && this.renderButton({ key: 'change-last-version', value: getLabel('521674', '切换至最新签批文件'), icon: 'icon-coms-synchronization' })}
        {
          toJS(RrightKeys).map((item) => {
            if ((device == 'EC' || isviewHistory) && (item.key === 'validBtn' || item.key === 'thumbBtn')) {
              return;
            }
            if (item.key === 'signFile' && toJS(sealDocs).length == 1) {
              return;
            }
            return this.renderButton(item);
          })
        }
        {(isviewHistory || device == 'EC') && isDownload && this.renderButton({key: "downloadBtn", value:`${downloadBtnName==""? getLabel('258', '下载'):downloadBtnName}`, icon: "icon-coms-download2"})}
        {isviewHistory && <span className={'wea-viewHistory-span'}>{getLabel('511897', '历史版本')}：{historyVersionName}</span>}
      </div>
    </div>);
  }

  doMenuClick = (item) => {
    let { setProperty, historyImagefiles, convertFile, isUsePDFViewer } = this.props.odocSignApprovalStore;
    toJS(historyImagefiles).forEach((data) => {
      if (data.id == item.key) {
        let encodeImageFileId = data.encodeimagefileid;
        setProperty({
          isviewHistory: true,
          historyImagefileid: encodeImageFileId,
          imagefileid: data.imagefileid,
          HistoryQianSelectedKeys: [`${data.id}`],
        });
        if (isUsePDFViewer == true) {
          convertFile();
        } else {
          jQuery('#historyPdf')[0].contentWindow.location.reload();
        }
      }
    });
  }

  doQianPiMenuClick = (item) => {
    let { ctx, setProperty, sealDocs, QianSelectedKeys, device, isUsePDFViewer, convertFile, qpSelected } = this.props.odocSignApprovalStore;
    if (item.key != toJS(QianSelectedKeys)[0]) {
      if (device != 'EC') {
        let newQpSelected = qpSelected;
        let changeQianPiFun = () => {
          jQuery('#ctx').empty();
          toJS(sealDocs).forEach((datas) => {
            if (datas.sequenceId == item.key) {
              if (newQpSelected == true) {
                setProperty({ qpSelected: true });
              }
              setProperty({
                sequenceId: item.key,
                QianSelectedKeys: [`${item.key}`],
                sealName: datas.imagefilename,
                sealid: datas.id,
                historyImagefileid: datas.encodeimagefileid,
                imagefileid: datas.imagefileid,
                showThumb: false,
              });
              this.loadSignApprovalPage();
            }
          });
        };
        ctx.CloseWrite();
        if (ctx.CheckoutHasUnsaveData()) {
          this.doIsSaveTip(changeQianPiFun);
        } else {
          changeQianPiFun();
        }
      } else {
        toJS(sealDocs).forEach((datas) => {
          if (datas.sequenceId == item.key) {
            setProperty({
              sequenceId: item.key,
              QianSelectedKeys: [`${item.key}`],
              sealName: datas.imagefilename,
              sealid: datas.id,
              historyImagefileid: datas.encodeimagefileid,
              imagefileid: datas.imagefileid,
            });
            if (isUsePDFViewer == true) {
              convertFile();
            } else {
              jQuery('#historyPdf')[0].contentWindow.location.reload();
            }
          }
        });
      }
    }
  }

  doIsSaveTip = (callback) => {
    let { setProperty, ctx } = this.props.odocSignApprovalStore;
    let saveCheck = '1';
    let _that = this;
    confirm({
      title: getLabel('131329', '信息确认'),
      content: <div>
        <p>{getLabel('521675', '当前签批文件未保存，是否要离开？')}</p>
        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@nrueve`}
          id="saveQian"
          value={saveCheck}
          onChange={(v) => { saveCheck = v; }}
        />
        <span style={{ marginLeft: '5px', verticalAlign: 'middle' }}>{getLabel('521676', '保存当前签批文件')}</span>
      </div>,
      onOk() {
        if (saveCheck == '1') {
          ctx.SimulateClickBtn('wsSaveBtn');
          setProperty({ isSave: true });
          let timer = setInterval(() => {
            if (_that.props.odocSignApprovalStore.isSave == false) {
              clearInterval(timer);
              callback();
            }
          }, 500);
        } else {
          callback();
        }
      },
      onCancel() { },
    });
  }

  doHistoryMenuClick = (menuItem) => {
    let { histroyDocs, setProperty, ctx, HistorySelectedKeys, device, isUsePDFViewer, convertFile, qpSelected } = this.props.odocSignApprovalStore;
    let hisotryDocsLen = toJS(histroyDocs).length;
    if (toJS(HistorySelectedKeys)[0] != menuItem.key) {
      if (device != 'EC') {
        let newQpSelected = qpSelected;
        let changeHistoryFunc = () => {
          setProperty({ HistorySelectedKeys: [menuItem.key] });
          toJS(histroyDocs).forEach((item, index) => {
            if (item.logid == menuItem.key) {
              let imagefileEntities = item.imagefileEntities;
              setProperty({
                isviewHistory: true,
                historyImagefiles: imagefileEntities,
                historyImagefileid: imagefileEntities[0].encodeimagefileid,
                imagefileid: imagefileEntities[0].imagefileid,
                historyVersionName: `${item.versionName}（V${hisotryDocsLen - index})`,
                HistoryQianSelectedKeys: [`${imagefileEntities[0].id}`],
                HistorySelectedKeys: [`${item.logid}`],
              });
              if (isUsePDFViewer == true) {
                convertFile();
              }
            }
          });
          if (newQpSelected == true) {
            setProperty({
              qpSelected: true,
            });
            ctx.SimulateClickBtn('writeBtn');
          }
        };
        ctx.CloseWrite();
        if (ctx.CheckoutHasUnsaveData()) {
          this.doIsSaveTip(changeHistoryFunc);
        } else {
          changeHistoryFunc();
        }
      } else {
        setProperty({ HistorySelectedKeys: [menuItem.key] });
        histroyDocs.forEach((item, index) => {
          if (item.logid == menuItem.key) {
            let imagefileEntities = item.imagefileEntities;
            setProperty({
              isviewHistory: true,
              historyImagefiles: imagefileEntities,
              historyImagefileid: imagefileEntities[0].encodeimagefileid,
              imagefileid: imagefileEntities[0].imagefileid,
              historyVersionName: `${item.versionName}（V${hisotryDocsLen - index})`,
              HistoryQianSelectedKeys: [`${imagefileEntities[0].id}`],
              HistorySelectedKeys: [`${item.logid}`],
            });
            if (isUsePDFViewer == true) {
              convertFile();
            } else {
              jQuery('#historyPdf')[0].contentWindow.location.reload();
            }
          }
        });
      }
    }
  }

  getQianFileMen = () => {
    let { isviewHistory, sealDocs, historyImagefiles, HistoryQianSelectedKeys, QianSelectedKeys } = this.props.odocSignApprovalStore;
    if (isviewHistory) {
      return (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@4wz6wb`} onClick={this.doMenuClick} selectedKeys={toJS(HistoryQianSelectedKeys)} style={{ maxWidth: '200px' }}>
        {toJS(historyImagefiles).map((item, index) => <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@eqasgb@${index}`} key={item.id} title={item.imagefilename.replace('.pdf', '')} className={'wea-sign-approval-dropdown-li'}>{item.imagefilename.replace('.pdf', '')}</Menu.Item>)}
      </Menu>);
    }
    return (<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@ookwqw`} onClick={this.doQianPiMenuClick} selectedKeys={toJS(QianSelectedKeys)} style={{ maxWidth: '200px' }}>
      {toJS(sealDocs).map((item, index) => <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@a6b91r@${index}`} key={item.sequenceId} title={item.imagefilename.replace('.pdf', '')} className={'wea-sign-approval-dropdown-li'}>{item.imagefilename.replace('.pdf', '')}</Menu.Item>)}
    </Menu>);
  }

  renderButton = (item) => {
    let { ctx, scale, setProperty, histroyDocs, HistorySelectedKeys, showThumb, qpSelected, device, sealDocs, sequenceId, isUsePDFViewer, convertFile, updateHeaderPosition,historyImagefileid } = this.props.odocSignApprovalStore;
    let historyDocLen = toJS(histroyDocs).length;
    let disabled = false;
    if (item.key === 'wsZoomInBtn' && scale == 0) {
      // disabled = true;
    } else if (item.key === 'wsZoomOutBtn' && scale == 3) {
      // disabled = true;
    } else if (item.key === 'thumbBtn' && showThumb == false) {
      disabled = true;
    } else if (item.key === 'validBtn' && showThumb == true) {
      disabled = true;
    }
    if (item.key == 'viewHistory') {
      if (historyDocLen > 0) {
        return (<Dropdown ecId={`${this && this.props && this.props.ecId || ''}_Dropdown@cm27v1`}
          trigger={['click']}
          overlay={
            <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@f34emn`} onClick={this.doHistoryMenuClick} selectedKeys={toJS(HistorySelectedKeys)}>
              {toJS(histroyDocs).map((items, index) => <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@on4huk@${index}`} key={items.logid} className={'wea-sign-approval-dropdown-li'}>V{historyDocLen - index}：{items.versionName}</Menu.Item>)}
            </Menu>
          }
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xd86w0`} type={'ghost'}><i className={item.icon} /><span>{item.value}</span><i className="icon-coms-down2" /></Button>
        </Dropdown>);
      }
      return;
    } else if (item.key == 'signFile') {
      return (<Dropdown ecId={`${this && this.props && this.props.ecId || ''}_Dropdown@lpfo4i`}
        trigger={['click']}
        overlay={
          this.getQianFileMen()
        }
      >
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l9xzz1`} type={'ghost'}><i className={item.icon} /><span>{item.value}</span><i className="icon-coms-down2" /></Button>
      </Dropdown>);
    }
    return (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bh2u1r`}
      type={'ghost'}
      className={`${item.key === 'writeBtn' ? 'wea-write-qp-btn' : ''} ${(item.key === 'writeBtn' && qpSelected) ? 'wea-write-btn-selected' : ''} ${disabled == true ? 'wea-sign-approval-has-selected' : ''}`}
      onClick={() => {
        if (item.key == 'change-last-version') {
          setProperty({ isviewHistory: false, HistorySelectedKeys: [] });
          toJS(sealDocs).forEach(datas => {
            if (datas.sequenceId == sequenceId) {
              setProperty({
                historyImagefileid: datas.encodeimagefileid,
                imagefileid: datas.imagefileid
              });
            }
          })
          if (device == 'EC') {
            toJS(sealDocs).forEach((datas) => {
              if (datas.sequenceId == sequenceId) {
                if (isUsePDFViewer == true) {
                  convertFile();
                } else {
                  jQuery('#historyPdf')[0].contentWindow.location.reload();
                }
              }
            });
          } else {
            setTimeout(() => {
              updateHeaderPosition();
            }, 300);
          }
        } else if (item.key == "downloadBtn") {
          window.open(`/weaver/weaver.file.FileDownload?fileid=${historyImagefileid}&download=1`)
        }  else {
          if (item.key != 'wsSaveBtn') {
            ctx.SimulateClickBtn(item.key);
          }
          if (item.key === 'wsZoomInBtn') {
            if (scale > 0) {
              setProperty({ scale: scale - 1 });
            }
          } else if (item.key === 'wsZoomOutBtn') {
            if (scale < 3) {
              setProperty({ scale: scale + 1 });
            }
          } else if (item.key === 'thumbBtn') {
            setProperty({ showThumb: false });
          } else if (item.key === 'validBtn') {
            setProperty({ showThumb: true });
          } else if (item.key === 'writeBtn') {
            if (qpSelected == true) {
              setProperty({ qpSelected: false });
            } else {
              setProperty({ qpSelected: true });
            }
          } else if (item.key === 'wsSaveBtn') {
            let newQpSelected = qpSelected;
            ctx.CloseWrite();
            if (ctx.CheckoutHasUnsaveData()) {
              if (newQpSelected == true) {
                setProperty({ isClickSave: true });
              }
              ctx.SimulateClickBtn(item.key);
            } else {
              if (newQpSelected == true) {
                ctx.SimulateClickBtn('writeBtn');
                setProperty({
                  qpSelected: true,
                });
              }
              message.warning(getLabel('524496','暂无未保存的内容'));
            }
          }
        }
      }}
    ><div><i className={item.icon} /><span>{item.value}</span></div></Button>);
  }

  render() {
    let { hasLoad, isviewHistory, historyImagefileid, device, histroyDocs, sealDocs, isUsePDFViewer, previewUrl, loading } = this.props.odocSignApprovalStore;
    let historyIframeHeight = 'calc(100% - 60px)';
    let showTopButtons = true;
    if (device == 'EC' && toJS(sealDocs).length == 1 && toJS(histroyDocs).length < 1) {
      historyIframeHeight = '100%';
      showTopButtons = false;
    }
    return (
      <div style={{ height: '100%', width: '100%' }}>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@fvaxv0`} spinning={loading} size={'large'}>
          <div style={{ height: '100vh' }}>
            {hasLoad && showTopButtons && this.getTopButton()}
            {device != 'EC' && <div id="ctx" style={{ height: `${isviewHistory ? '0px' : 'calc(100% - 60px)'}`, width: '100%' }} className={'wea-haoqian-box'} />}
            {
              (isviewHistory || device == 'EC') && isUsePDFViewer != true && <div className={'wea-haoqian-history-version'} style={{ height: historyIframeHeight }}>
                <iframe id="historyPdf" src={`/docs/pdfview/web/pdfViewer.jsp?canPrint=false&canDownload=false&pdfimagefileid=${historyImagefileid}`} style={{ width: '100%', height: '100%' }} title="historyPdf" />
              </div>
            }
            {
              (isviewHistory || device == 'EC') && isUsePDFViewer == true && <div className={'wea-haoqian-history-version'} style={{ height: historyIframeHeight }}>
                <iframe id="historyPdf" src={previewUrl} style={{ width: '100%', height: '100%' }} title="historyPdf" />
              </div>
            }
          </div>
        </Spin>
      </div>

    );
  }
}
